// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        shaderName: ''
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start() {
        this.time = 0;
        this.setShader(this.shaderName);
    },

    setShader: function (shaderName) {
        if (shaderName == '') {
            return;
        }

        var glProgram = new cc.GLProgram();
        this.glProgram = glProgram;

        var vert = require(cc.js.formatStr("%s.vert", shaderName));
        var frag = require(cc.js.formatStr("%s.frag", shaderName));
        glProgram.initWithString(vert, frag);
        if (!cc.sys.isNative) {
            glProgram.initWithVertexShaderByteArray(vert, frag);
            glProgram.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION);
            glProgram.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR);
            glProgram.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS);
            glProgram.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS);
        }

        glProgram.link();
        glProgram.updateUniforms();
        this.node.getComponent(cc.Sprite)._sgNode.setShaderProgram(glProgram);   
    },

    update(dt) {
        if (this.glProgram) {
            this.glProgram.use();
            if (cc.sys.isNative) {
                var glProgram_state = cc.GLProgramState.getOrCreateWithGLProgram(this.glProgram);
                glProgram_state.setUniformFloat("u_time", this.time);
            } else {
                let ct = this.glProgram.getUniformLocationForName("u_time");
                this.glProgram.setUniformLocationWith1f(ct, this.time);
            }
            this.time = this.time + dt * 0.1;
        }
    },
});
